package com.aplikata.evok.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.aplikata.bo.User;
import com.aplikata.constants.Constants;
import com.aplikata.constants.ConstantsMsg;
import com.aplikata.dao.ParameterDao;
import com.aplikata.dao.UserDao;
import com.aplikata.evok.constants.EvokConstants;
import com.aplikata.exception.CustomException;
import com.aplikata.service.PublicServiceImpl;
import com.aplikata.util.FacesUtil;
import com.aplikata.util.YunDateUtil;
import com.aplikata.util.encoder.MD5PasswordEncoder;
import com.aplikata.util.encoder.PasswordEncoder;

@Service("evokUserService")
public class EvokUserServiceImpl extends PublicServiceImpl implements EvokUserService {
	
	@Autowired
	private UserDao userDao;

	@Autowired
	private ParameterDao parameterDao;
	
	public EvokUserServiceImpl() {
	}

	@SuppressWarnings({ })
	@Override
	public String submitMobileLogin(String userName, String userPwd) throws Exception {
		User user = userDao.findSingleByProperty(User.USER_NAME, userName);
		if (user == null) {
			throw new CustomException(ConstantsMsg.LOGIN_BADNAMEPWD);
		}

		PasswordEncoder encoder = new MD5PasswordEncoder();
		if (!encoder.encode(userPwd).equals(user.getUserPwd())) {
			throw new CustomException(ConstantsMsg.LOGIN_BADNAMEPWD);
		}

		if (Constants.COMMON_STATUS_NORMAL != user.getStatus()) {
			throw new CustomException(ConstantsMsg.LOGIN_STATUSNOTNORMAL);
		}	
		
		String sql = "SELECT dr.* FROM _domain_role dr, _role r " +
				" where dr.domain_id=" + user.getDomain().getId() + " and dr.role_id = r.id and r.name like 'mobile%'";
		
		Object object = this.findSingleBySql(sql);
		if(object == null){
			throw new CustomException(ConstantsMsg.LOGIN_STATUSNOTNORMAL);
		}
			
		user.setLastLoginTime(YunDateUtil.getDateTime());
		user = userDao.merge(user);
		
		FacesUtil.setManagedBeanInSession(Constants.SESSION_ENUM, parameterDao.getEnumMap());
		FacesUtil.setManagedBeanInSession(Constants.SESSION_USER, user);
		FacesUtil.setManagedBeanInSession(Constants.SESSION_DOMAIN, user.getDomain());
		
		String roleName = user.getRole().getName();
		if (roleName.startsWith("doc-")) {
			return EvokConstants.MOBILE_VIEW_DOCTOR_RESERVATION;
		}

		return null;
	}
}
